package com.team9.fitness.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.team9.fitness.dto.FitnessRequest;
import com.team9.fitness.dto.FitnessResponse;
import com.team9.fitness.dto.SignInDTO;
import com.team9.fitness.dto.SignUpDTO;
import com.team9.fitness.entity.*;
import com.team9.fitness.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Optional;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.io.File;

// ZRDDS相关导入
import com.zrdds.simpleinterface.DDSIF;
import com.zrdds.domain.DomainParticipant;
import com.zrdds.domain.DomainParticipantFactory;
import com.zrdds.subscription.DataReader;
import com.zrdds.subscription.SimpleDataReaderListener;
import com.zrdds.infrastructure.BytesTypeSupport;
import com.zrdds.infrastructure.ReturnCode_t;
import com.zrdds.infrastructure.SampleInfo;
import com.zrdds.infrastructure.Bytes;
import com.zrdds.infrastructure.BytesSeq;
import com.zrdds.infrastructure.BytesDataReader;
import com.zrdds.publication.DataWriter;

/**
 * ZRDDS数据监听器
 * 负责接收和处理来自fitness-send模块的请求
 */
@Slf4j
@Component
public class ZRDDSDataListener {

    @Value("${zrdds.domain-id:0}")
    private int domainId;

    @Value("${zrdds.qos-profile:default_profile}")
    private String qosProfile;

    @Value("${zrdds.receive.topic-name:fitness-request}")
    private String receiveTopicName;

    @Value("${zrdds.send.topic-name:fitness-response}")
    private String sendTopicName;

    @Autowired
    private UserService userService;

    @Autowired
    private ExerciseRecordService exerciseRecordService;

    @Autowired
    private DietService dietService;

    @Autowired
    private DietRecordService dietRecordService;

    @Autowired
    private UserProfileService userProfileService;

    @Autowired
    private CommunityPostService communityPostService;

    @Autowired
    private PostCommentService postCommentService;

    @Autowired
    private PostLikeService postLikeService;

    @Autowired
    private PostFavoriteService postFavoriteService;

    @Autowired
    private CommentLikeService commentLikeService;

    @Autowired
    private ExerciseInfoService exerciseInfoService;

    @Autowired
    private FoodInfoService foodInfoService;

    @Autowired
    private UserAvatarService userAvatarService;

    @Autowired
    private ObjectMapper objectMapper;

    // 线程池用于异步处理请求 - 优化配置
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(
        Math.max(4, Runtime.getRuntime().availableProcessors()), // 根据CPU核心数调整
        r -> {
            Thread t = new Thread(r, "ZRDDS-Request-Processor");
            t.setDaemon(true);
            return t;
        }
    );

    // ZRDDS相关组件
    private DomainParticipant participant;
    private DataReader requestReader;
    private DataWriter responseWriter;

    /**
     * 初始化数据监听器
     */
    @PostConstruct
    public void initialize() {
        try {
            log.info("初始化ZRDDS数据监听器...");

            // 初始化ZRDDS监听器
            initializeZRDDSListener();

            log.info("ZRDDS数据监听器初始化完成");

        } catch (Exception e) {
            log.error("初始化ZRDDS数据监听器失败", e);
        }
    }

    /**
     * 初始化ZRDDS监听器
     */
    private void initializeZRDDSListener() {
        try {
            // 使用绝对路径加载ZRDDS库
            String projectRoot = System.getProperty("user.dir");
            String dllPath = projectRoot + File.separator + "lib" + File.separator + "ZRDDS_JAVA.dll";
            
            // 检查DLL文件是否存在
            File dllFile = new File(dllPath);
            if (!dllFile.exists()) {
                throw new RuntimeException("ZRDDS_JAVA.dll文件不存在: " + dllPath);
            }
            
            // 设置库路径到系统属性，确保ZRDDS中间件能找到库
            String libPath = projectRoot + File.separator + "lib";
            String currentLibraryPath = System.getProperty("java.library.path");
            if (currentLibraryPath == null || !currentLibraryPath.contains(libPath)) {
                String newLibraryPath = currentLibraryPath == null ? libPath : currentLibraryPath + File.pathSeparator + libPath;
                System.setProperty("java.library.path", newLibraryPath);
                
                // 重新加载库路径
                try {
                    java.lang.reflect.Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
                    fieldSysPath.setAccessible(true);
                    fieldSysPath.set(null, null);
                    log.info("已重新加载库路径: {}", newLibraryPath);
                } catch (Exception e) {
                    log.warn("无法重新加载库路径: {}", e.getMessage());
                }
            }
            
            // 使用绝对路径加载库
            System.load(dllPath);
            log.info("成功加载ZRDDS库: {}", dllPath);

            // 初始化ZRDDS中间件
            DomainParticipantFactory factory = DDSIF.init("ZRDDS_QOS_PROFILES.xml", "default");
            if (factory == null) {
                throw new RuntimeException("ZRDDS中间件初始化失败");
            }

            // 创建域参与者
            participant = DDSIF.create_dp(domainId, qosProfile);
            if (participant == null) {
                throw new RuntimeException("创建域参与者失败");
            }

            // 创建请求订阅主题 - 接收来自fitness-send的请求
            requestReader = DDSIF.sub_topic(participant, receiveTopicName,
                    BytesTypeSupport.get_instance(), "reliable", new RequestListener());
            if (requestReader == null) {
                throw new RuntimeException("创建请求订阅主题失败");
            }

            // 创建响应发布主题 - 向fitness-send发送响应
            responseWriter = DDSIF.pub_topic(participant, sendTopicName,
                    BytesTypeSupport.get_instance(), "reliable", null);
            if (responseWriter == null) {
                throw new RuntimeException("创建响应发布主题失败");
            }

            log.info("ZRDDS监听器初始化成功 - 域ID: {}, 主题: {}", domainId, receiveTopicName);

        } catch (Exception e) {
            log.error("ZRDDS监听器初始化失败", e);
            throw new RuntimeException("ZRDDS监听器初始化失败", e);
        }
    }

    /**
     * 请求监听器
     */
    private class RequestListener extends SimpleDataReaderListener<Bytes, BytesSeq, BytesDataReader> {
        @Override
        public void on_process_sample(DataReader dataReader, Bytes bytes, SampleInfo sampleInfo) {
            try {
                // 将字节数据转换为请求字符串
                byte[] data = bytes.value.get_contiguous_buffer();
                int length = bytes.value.length();
                String requestData = new String(data, 0, length, "UTF-8");
                log.info("接收到ZRDDS请求数据: {}", requestData);

                // 异步处理请求，使用线程池优化性能
                scheduler.submit(() -> {
                    try {
                        handleRequest(requestData);
                    } catch (Exception e) {
                        log.error("异步处理ZRDDS请求失败", e);
                    }
                });
            } catch (Exception e) {
                log.error("处理ZRDDS请求数据失败", e);
            }
        }

        @Override
        public void on_data_arrived(DataReader dataReader, Object data, SampleInfo sampleInfo) {
            // 这个方法在SimpleDataReaderListener中是必须实现的，但不会被调用
        }
    }

    /**
     * 处理接收到的请求
     * 这个方法由ZRDDS回调触发
     */
    public void handleRequest(String requestData) {
        try {
            log.info("处理请求数据: {}", requestData);

            // 解析请求
            FitnessRequest request = objectMapper.readValue(requestData, FitnessRequest.class);
            String requestType = request.getRequestType();
            String requestId = request.getRequestId();

            log.info("处理请求类型: {}, 请求ID: {}", requestType, requestId);

            // 根据请求类型处理
            FitnessResponse response = processRequest(request);

            // 发送响应
            sendResponse(requestId, response);

        } catch (Exception e) {
            log.error("处理请求失败", e);
            // 发送错误响应
            try {
                FitnessResponse errorResponse = new FitnessResponse();
                errorResponse.setSuccess(false);
                errorResponse.setMessage("处理请求失败: " + e.getMessage());
                sendResponse("error", errorResponse);
            } catch (Exception ex) {
                log.error("发送错误响应失败", ex);
            }
        }
    }

    /**
     * 处理业务请求
     */
    private FitnessResponse processRequest(FitnessRequest request) {
        long startTime = System.currentTimeMillis();
        FitnessResponse response = new FitnessResponse();
        response.setRequestId(request.getRequestId());
        response.setTimestamp(System.currentTimeMillis());

        try {
            String requestType = request.getRequestType();
            log.info("处理请求: type={}, method={}, path={}", requestType, request.getMethod(), request.getPath());

            switch (requestType) {
                case "USER_LOGIN":
                    response = handleUserLogin(request);
                    break;
                case "USER_REGISTER":
                    response = handleUserRegister(request);
                    break;
                case "USER_GET_BY_ID":
                    response = handleUserGetById(request);
                    break;
                case "EXERCISE_START":
                    response = handleExerciseStart(request);
                    break;
                case "EXERCISE_END":
                    response = handleExerciseEnd(request);
                    break;
                case "EXERCISE_GET_BY_USER":
                    response = handleExerciseGetByUser(request);
                    break;
                case "EXERCISE_GET_BY_USER_STATUS":
                    response = handleExerciseGetByUserStatus(request);
                    break;
                case "EXERCISE_GET_BY_ID":
                    response = handleExerciseGetById(request);
                    break;
                case "DIET_SAVE":
                    response = handleDietSave(request);
                    break;
                case "DIET_GET_ALL":
                    response = handleDietGetAll(request);
                    break;
                case "USER_PROFILE_SAVE":
                    response = handleUserProfileSave(request);
                    break;
                case "USER_PROFILE_GET":
                    response = handleUserProfileGet(request);
                    break;
                case "AVATAR_UPLOAD":
                    response = handleAvatarUpload(request);
                    break;
                case "AVATAR_GET":
                    response = handleAvatarGet(request);
                    break;
                case "AVATAR_DELETE":
                    response = handleAvatarDelete(request);
                    break;
                case "COMMUNITY_CREATE_POST":
                    response = handleCommunityCreatePost(request);
                    break;
                case "COMMUNITY_GET_ALL_POSTS":
                    response = handleCommunityGetAllPosts(request);
                    break;
                case "COMMUNITY_GET_POST_BY_ID":
                    response = handleCommunityGetPostById(request);
                    break;
                case "COMMUNITY_GET_POST_QUICK":
                    response = handleCommunityGetPostQuick(request);
                    break;
                case "COMMUNITY_GET_POST_COMMENTS":
                    response = handleCommunityGetPostComments(request);
                    break;
                case "COMMUNITY_GET_USER_POSTS":
                    response = handleCommunityGetUserPosts(request);
                    break;
                case "COMMUNITY_UPDATE_POST":
                    response = handleCommunityUpdatePost(request);
                    break;
                case "COMMUNITY_DELETE_POST":
                    response = handleCommunityDeletePost(request);
                    break;
                case "POST_COMMENT_CREATE":
                    response = handlePostCommentCreate(request);
                    break;
                case "POST_COMMENT_GET_BY_POST":
                    response = handlePostCommentGetByPost(request);
                    break;
                case "POST_COMMENT_GET_BY_ID":
                    response = handlePostCommentGetById(request);
                    break;
                case "POST_COMMENT_GET_REPLIES":
                    response = handlePostCommentGetReplies(request);
                    break;
                case "POST_COMMENT_GET_COUNT":
                    response = handlePostCommentGetCount(request);
                    break;
                case "POST_COMMENT_GET_USER_COMMENTS":
                    response = handlePostCommentGetUserComments(request);
                    break;
                case "POST_COMMENT_DELETE":
                    response = handlePostCommentDelete(request);
                    break;
                case "POST_LIKE_TOGGLE":
                    response = handlePostLikeToggle(request);
                    break;
                case "POST_LIKE_GET_STATUS":
                    response = handlePostLikeGetStatus(request);
                    break;
                case "POST_LIKE_GET_COUNT":
                    response = handlePostLikeGetCount(request);
                    break;
                case "POST_FAVORITE_TOGGLE":
                    response = handlePostFavoriteToggle(request);
                    break;
                case "POST_FAVORITE_GET_STATUS":
                    response = handlePostFavoriteGetStatus(request);
                    break;
                case "POST_FAVORITE_GET_COUNT":
                    response = handlePostFavoriteGetCount(request);
                    break;
                case "POST_FAVORITE_GET_USER_FAVORITES":
                    response = handlePostFavoriteGetUserFavorites(request);
                    break;
                case "COMMENT_LIKE_TOGGLE":
                    response = handleCommentLikeToggle(request);
                    break;
                case "COMMENT_LIKE_GET_STATUS":
                    response = handleCommentLikeGetStatus(request);
                    break;
                case "COMMENT_LIKE_GET_COUNT":
                    response = handleCommentLikeGetCount(request);
                    break;
                case "EXERCISE_INFO_CREATE":
                    response = handleExerciseInfoCreate(request);
                    break;
                case "EXERCISE_INFO_GET_ALL":
                    response = handleExerciseInfoGetAll(request);
                    break;
                case "EXERCISE_INFO_GET_BY_ID":
                    response = handleExerciseInfoGetById(request);
                    break;
                case "EXERCISE_INFO_GET_BY_CATEGORY":
                    response = handleExerciseInfoGetByCategory(request);
                    break;
                case "EXERCISE_INFO_SEARCH":
                    response = handleExerciseInfoSearch(request);
                    break;
                case "EXERCISE_INFO_GET_CATEGORIES":
                    response = handleExerciseInfoGetCategories(request);
                    break;
                case "EXERCISE_INFO_UPDATE":
                    response = handleExerciseInfoUpdate(request);
                    break;
                case "EXERCISE_INFO_DELETE":
                    response = handleExerciseInfoDelete(request);
                    break;
                case "FOOD_INFO_GET_CATEGORIES":
                    response = handleFoodInfoGetCategories(request);
                    break;
                case "FOOD_INFO_GET_ALL":
                    response = handleFoodInfoGetAll(request);
                    break;
                case "FOOD_INFO_GET_BY_CATEGORY":
                    response = handleFoodInfoGetByCategory(request);
                    break;
                case "FOOD_INFO_GET_BY_ID":
                    response = handleFoodInfoGetById(request);
                    break;
                case "FOOD_INFO_SEARCH":
                    response = handleFoodInfoSearch(request);
                    break;
                case "DIET_RECORD_GET_SUMMARY":
                    response = handleDietRecordGetSummary(request);
                    break;
                case "DIET_RECORD_GET_BY_USER_DATE":
                    response = handleDietRecordGetByUserDate(request);
                    break;
                case "DIET_RECORD_CREATE":
                    response = handleDietRecordCreate(request);
                    break;
                default:
                    response.setSuccess(false);
                    response.setStatusCode(400);
                    response.setMessage("未知的请求类型: " + requestType);
                    log.warn("未知的请求类型: {}", requestType);
            }

            response.setExecutionTime(System.currentTimeMillis() - startTime);

        } catch (Exception e) {
            log.error("处理请求异常", e);
            response.setSuccess(false);
            response.setStatusCode(500);
            response.setMessage("处理请求失败: " + e.getMessage());
            response.setError(e.getMessage());
            response.setExecutionTime(System.currentTimeMillis() - startTime);
        }

        return response;
    }

    // 用户相关处理方法
    private FitnessResponse handleUserLogin(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String username = (String) body.get("username");
            String password = (String) body.get("password");

            SignInDTO signInDTO = new SignInDTO();
            signInDTO.setUsername(username);
            signInDTO.setPassword(password);

            ResponseEntity<Map<String, Object>> response = userService.signIn(signInDTO);
            Map<String, Object> result = response.getBody();
            return createSuccessResponse(result);
        } catch (Exception e) {
            log.error("处理用户登录失败", e);
            return createErrorResponse("用户登录失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleUserRegister(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String username = (String) body.get("username");
            String password = (String) body.get("password");
            String confirmPassword = (String) body.get("confirmPassword");

            SignUpDTO signUpDTO = new SignUpDTO();
            signUpDTO.setUsername(username);
            signUpDTO.setPassword(password);
            signUpDTO.setConfirmPassword(confirmPassword);

            ResponseEntity<Map<String, Object>> response = userService.signUp(signUpDTO);
            Map<String, Object> result = response.getBody();

            // 根据UserService返回的结果决定是成功还是失败响应
            if (result != null && Boolean.TRUE.equals(result.get("success"))) {
                return createSuccessResponse(result);
            } else {
                return createErrorResponse(result != null ? (String) result.get("message") : "注册失败");
            }
        } catch (Exception e) {
            log.error("处理用户注册失败", e);
            return createErrorResponse("用户注册失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleUserGetById(FitnessRequest request) {
        try {
            Long userId = Long.valueOf(request.getUserId());
            User user = userService.getUserById(userId);
            if (user != null) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("id", user.getId());
                resultMap.put("username", user.getUsername());
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("用户不存在");
            }
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return createErrorResponse("获取用户信息失败: " + e.getMessage());
        }
    }

    // 运动记录相关处理方法
    private FitnessResponse handleExerciseStart(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(body.get("userId").toString());
            Long exerciseId = Long.valueOf(body.get("exerciseId").toString());

            ExerciseRecord result = exerciseRecordService.startExerciseByZRDDS(userId, exerciseId);
            if (result != null) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("id", result.getId());
                resultMap.put("userId", result.getUserId());
                resultMap.put("exerciseId", result.getExerciseId());
                resultMap.put("startTime", result.getStartTime());
                resultMap.put("status", result.getStatus());
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("开始运动失败");
            }
        } catch (Exception e) {
            log.error("处理运动开始失败", e);
            return createErrorResponse("运动开始失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseEnd(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long recordId = Long.valueOf(body.get("recordId").toString());
            Double avgHeartRate = body.get("avgHeartRate") != null ? Double.valueOf(body.get("avgHeartRate").toString())
                    : null;
            Double maxHeartRate = body.get("maxHeartRate") != null ? Double.valueOf(body.get("maxHeartRate").toString())
                    : null;
            Double avgSpeed = body.get("avgSpeed") != null ? Double.valueOf(body.get("avgSpeed").toString()) : null;
            Double maxSpeed = body.get("maxSpeed") != null ? Double.valueOf(body.get("maxSpeed").toString()) : null;

            ExerciseRecord result = exerciseRecordService.endExerciseByZRDDS(recordId, avgHeartRate, maxHeartRate,
                    avgSpeed, maxSpeed);
            if (result != null) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("id", result.getId());
                resultMap.put("userId", result.getUserId());
                resultMap.put("exerciseId", result.getExerciseId());
                resultMap.put("startTime", result.getStartTime());
                resultMap.put("endTime", result.getEndTime());
                resultMap.put("status", result.getStatus());
                resultMap.put("avgHeartRate", result.getAvgHeartRate());
                resultMap.put("maxHeartRate", result.getMaxHeartRate());
                resultMap.put("avgSpeed", result.getAvgSpeed());
                resultMap.put("maxSpeed", result.getMaxSpeed());
                resultMap.put("duration", result.getDuration());
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("结束运动失败");
            }
        } catch (Exception e) {
            log.error("处理运动结束失败", e);
            return createErrorResponse("运动结束失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseGetByUser(FitnessRequest request) {
        try {
            Long userId = Long.valueOf(request.getUserId());
            List<ExerciseRecord> records = exerciseRecordService.getExerciseRecordsByUserId(userId);
            if (records != null && !records.isEmpty()) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("records", records);
                resultMap.put("count", records.size());
                return createSuccessResponse(resultMap);
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("records", new ArrayList<>());
                resultMap.put("count", 0);
                return createSuccessResponse(resultMap);
            }
        } catch (Exception e) {
            log.error("获取用户运动记录失败", e);
            return createErrorResponse("获取用户运动记录失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseGetByUserStatus(FitnessRequest request) {
        try {
            Long userId = Long.valueOf(request.getUserId());
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String status = (String) body.get("status");

            List<ExerciseRecord> records = exerciseRecordService.getExerciseRecordsByUserIdAndStatus(userId, status);
            if (records != null && !records.isEmpty()) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("records", records);
                resultMap.put("count", records.size());
                resultMap.put("status", status);
                return createSuccessResponse(resultMap);
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("records", new ArrayList<>());
                resultMap.put("count", 0);
                resultMap.put("status", status);
                return createSuccessResponse(resultMap);
            }
        } catch (Exception e) {
            log.error("获取用户指定状态运动记录失败", e);
            return createErrorResponse("获取用户指定状态运动记录失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseGetById(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long id = Long.valueOf(body.get("id").toString());

            ExerciseRecord record = exerciseRecordService.getExerciseRecordById(id);
            if (record != null) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("id", record.getId());
                resultMap.put("userId", record.getUserId());
                resultMap.put("exerciseId", record.getExerciseId());
                resultMap.put("startTime", record.getStartTime());
                resultMap.put("endTime", record.getEndTime());
                resultMap.put("status", record.getStatus());
                resultMap.put("avgHeartRate", record.getAvgHeartRate());
                resultMap.put("maxHeartRate", record.getMaxHeartRate());
                resultMap.put("avgSpeed", record.getAvgSpeed());
                resultMap.put("maxSpeed", record.getMaxSpeed());
                resultMap.put("duration", record.getDuration());
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("运动记录不存在");
            }
        } catch (Exception e) {
            log.error("获取运动记录失败", e);
            return createErrorResponse("获取运动记录失败: " + e.getMessage());
        }
    }

    // 饮食相关处理方法
    private FitnessResponse handleDietSave(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long id = Long.valueOf(body.get("id").toString());
            @SuppressWarnings("unchecked")
            java.util.List<com.team9.fitness.entity.Diet> diets = (java.util.List<com.team9.fitness.entity.Diet>) body
                    .get("diets");

            ResponseEntity<Map<String, Object>> response = dietService.save(id, diets);
            Map<String, Object> result = response.getBody();
            return createSuccessResponse(result);
        } catch (Exception e) {
            log.error("保存饮食计划失败", e);
            return createErrorResponse("保存饮食计划失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleDietGetAll(FitnessRequest request) {
        try {
            ResponseEntity<Map<String, Object>> response = dietService.getAll();
            Map<String, Object> result = response.getBody();
            return createSuccessResponse(result);
        } catch (Exception e) {
            log.error("获取饮食计划失败", e);
            return createErrorResponse("获取饮食计划失败: " + e.getMessage());
        }
    }

    // 用户个人信息相关处理方法
    private FitnessResponse handleUserProfileSave(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            com.team9.fitness.entity.UserProfile userProfile = objectMapper.convertValue(body.get("userProfile"),
                    com.team9.fitness.entity.UserProfile.class);

            // 调用UserProfileService的保存方法
            UserProfile savedProfile = userProfileService.saveOrUpdateUserProfile(userProfile);
            if (savedProfile != null && savedProfile.getId() != null) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("success", true);
                resultMap.put("message", "用户资料保存成功");
                resultMap.put("id", savedProfile.getId());
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("用户资料保存失败");
            }
        } catch (Exception e) {
            log.error("保存用户个人信息失败", e);
            return createErrorResponse("保存用户个人信息失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleUserProfileGet(FitnessRequest request) {
        try {
            Long userId = Long.valueOf(request.getUserId());
            com.team9.fitness.entity.UserProfile userProfile = userProfileService.getUserProfileByUserId(userId);
            if (userProfile != null) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("id", userProfile.getId());
                resultMap.put("userId", userProfile.getUserId());
                resultMap.put("name", userProfile.getName());
                resultMap.put("height", userProfile.getHeight());
                resultMap.put("weight", userProfile.getWeight());
                resultMap.put("gender", userProfile.getGender());
                resultMap.put("birthday", userProfile.getBirthday());
                resultMap.put("des", userProfile.getDes());
                resultMap.put("location", userProfile.getLocation());
                resultMap.put("avatar", userProfile.getAvatar());
                resultMap.put("createdAt", userProfile.getCreatedAt());
                resultMap.put("updatedAt", userProfile.getUpdatedAt());
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("用户资料不存在");
            }
        } catch (Exception e) {
            log.error("获取用户个人信息失败", e);
            return createErrorResponse("获取用户个人信息失败: " + e.getMessage());
        }
    }

    // 社区相关处理方法
    private FitnessResponse handleCommunityCreatePost(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            com.team9.fitness.entity.CommunityPost post = objectMapper.convertValue(body.get("post"),
                    com.team9.fitness.entity.CommunityPost.class);

            CommunityPost createdPost = communityPostService.createPost(post);
            if (createdPost != null && createdPost.getId() != null) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("id", createdPost.getId());
                resultMap.put("userId", createdPost.getUserId());
                resultMap.put("title", createdPost.getTitle());
                resultMap.put("content", createdPost.getContent());
                resultMap.put("createdAt", createdPost.getCreatedAt());
                resultMap.put("message", "社区帖子创建成功");
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("社区帖子创建失败");
            }
        } catch (Exception e) {
            log.error("创建社区帖子失败", e);
            return createErrorResponse("创建社区帖子失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleCommunityGetAllPosts(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long currentUserId = body.get("currentUserId") != null ? Long.valueOf(body.get("currentUserId").toString())
                    : null;

            List<CommunityPost> posts = communityPostService.getAllPosts(currentUserId);
            if (posts != null && !posts.isEmpty()) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("posts", posts);
                resultMap.put("count", posts.size());
                return createSuccessResponse(resultMap);
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("posts", new ArrayList<>());
                resultMap.put("count", 0);
                return createSuccessResponse(resultMap);
            }
        } catch (Exception e) {
            log.error("获取社区帖子失败", e);
            return createErrorResponse("获取社区帖子失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleCommunityGetPostById(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long postId = body.get("postId") != null ? Long.valueOf(body.get("postId").toString()) : null;
            Long currentUserId = body.get("currentUserId") != null ? Long.valueOf(body.get("currentUserId").toString())
                    : null;

            if (postId == null) {
                return createErrorResponse("帖子ID不能为空");
            }

            Optional<CommunityPost> postOpt = communityPostService.getPostById(postId, currentUserId);
            if (postOpt.isPresent()) {
                CommunityPost post = postOpt.get();
                return createSuccessResponse(post);
            } else {
                return createErrorResponse("帖子不存在或已被删除");
            }
        } catch (Exception e) {
            log.error("获取单个社区帖子失败", e);
            return createErrorResponse("获取帖子详情失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleCommunityGetUserPosts(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(body.get("userId").toString());
            int page = body.get("page") != null ? Integer.parseInt(body.get("page").toString()) : 1;
            int size = body.get("size") != null ? Integer.parseInt(body.get("size").toString()) : 10;

            List<CommunityPost> posts = communityPostService.getUserPosts(userId, page, size);
            int totalCount = communityPostService.getUserPostCount(userId);

            log.info("获取用户帖子列表结果: userId={}, page={}, size={}, postsCount={}, totalCount={}", 
                    userId, page, size, posts.size(), totalCount);
            
            // 打印每个帖子的详细信息
            for (CommunityPost post : posts) {
                log.info("帖子详情: id={}, title={}, commentCount={}, likeCount={}, favoriteCount={}", 
                        post.getId(), post.getTitle(), post.getCommentCount(), post.getLikeCount(), post.getFavoriteCount());
            }

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("posts", posts);
            resultMap.put("count", posts.size());
            resultMap.put("totalCount", totalCount);
            resultMap.put("page", page);
            resultMap.put("size", size);
            resultMap.put("hasMore", (page * size) < totalCount);

            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取用户帖子列表失败", e);
            return createErrorResponse("获取用户帖子列表失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleCommunityUpdatePost(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long postId = Long.valueOf(body.get("postId").toString());
            Map<String, Object> postData = (Map<String, Object>) body.get("post");

            CommunityPost post = new CommunityPost();
            post.setId(postId);
            post.setUserId(Long.valueOf(postData.get("userId").toString()));
            post.setTitle((String) postData.get("title"));
            post.setContent((String) postData.get("content"));

            boolean success = communityPostService.updatePostWithResult(post);
            if (success) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("success", true);
                resultMap.put("message", "帖子更新成功");
                resultMap.put("postId", postId);
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("帖子更新失败");
            }
        } catch (Exception e) {
            log.error("更新帖子失败", e);
            return createErrorResponse("更新帖子失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleCommunityDeletePost(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long postId = Long.valueOf(body.get("postId").toString());
            Long userId = Long.valueOf(body.get("userId").toString());

            boolean success = communityPostService.deletePost(postId, userId);
            if (success) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("success", true);
                resultMap.put("message", "帖子删除成功");
                resultMap.put("postId", postId);
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("帖子删除失败，可能没有权限或帖子不存在");
            }
        } catch (Exception e) {
            log.error("删除帖子失败", e);
            return createErrorResponse("删除帖子失败: " + e.getMessage());
        }
    }

    // 帖子评论相关处理方法（已移动到文件末尾，避免重复定义）

    // handlePostCommentGetByPost方法已移动到文件末尾，避免重复定义

    // handlePostCommentGetCount方法已移动到文件末尾，避免重复定义

    // 帖子点赞相关处理方法
    private FitnessResponse handlePostLikeToggle(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(body.get("userId").toString());
            Long postId = Long.valueOf(body.get("postId").toString());

            boolean result = postLikeService.togglePostLike(userId, postId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("success", result);
            resultMap.put("message", result ? "点赞状态切换成功" : "点赞状态切换失败");
            resultMap.put("userId", userId);
            resultMap.put("postId", postId);
            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("切换帖子点赞状态失败", e);
            return createErrorResponse("切换帖子点赞状态失败: " + e.getMessage());
        }
    }

    private FitnessResponse handlePostLikeGetStatus(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(body.get("userId").toString());
            Long postId = Long.valueOf(body.get("postId").toString());

            Boolean result = postLikeService.getUserLikeStatus(userId, postId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("isLiked", result);
            resultMap.put("userId", userId);
            resultMap.put("postId", postId);
            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取帖子点赞状态失败", e);
            return createErrorResponse("获取帖子点赞状态失败: " + e.getMessage());
        }
    }

    private FitnessResponse handlePostLikeGetCount(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long postId = Long.valueOf(body.get("postId").toString());

            int result = postLikeService.getPostLikeCount(postId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("likeCount", result);
            resultMap.put("postId", postId);
            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取帖子点赞数量失败", e);
            return createErrorResponse("获取帖子点赞数量失败: " + e.getMessage());
        }
    }

    // 帖子收藏相关处理方法
    private FitnessResponse handlePostFavoriteToggle(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(body.get("userId").toString());
            Long postId = Long.valueOf(body.get("postId").toString());

            boolean result = postFavoriteService.togglePostFavorite(userId, postId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("success", result);
            resultMap.put("message", result ? "收藏状态切换成功" : "收藏状态切换失败");
            resultMap.put("userId", userId);
            resultMap.put("postId", postId);
            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("切换帖子收藏状态失败", e);
            return createErrorResponse("切换帖子收藏状态失败: " + e.getMessage());
        }
    }

    private FitnessResponse handlePostFavoriteGetStatus(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(body.get("userId").toString());
            Long postId = Long.valueOf(body.get("postId").toString());

            Boolean result = postFavoriteService.getUserFavoriteStatus(userId, postId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("isFavorited", result);
            resultMap.put("userId", userId);
            resultMap.put("postId", postId);
            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取帖子收藏状态失败", e);
            return createErrorResponse("获取帖子收藏状态失败: " + e.getMessage());
        }
    }

    private FitnessResponse handlePostFavoriteGetCount(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long postId = Long.valueOf(body.get("postId").toString());

            int result = postFavoriteService.getPostFavoriteCount(postId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("favoriteCount", result);
            resultMap.put("postId", postId);
            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取帖子收藏数量失败", e);
            return createErrorResponse("获取帖子收藏数量失败: " + e.getMessage());
        }
    }

    /**
     * 处理获取用户收藏列表请求
     */
    private FitnessResponse handlePostFavoriteGetUserFavorites(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(body.get("userId").toString());
            int page = body.get("page") != null ? Integer.parseInt(body.get("page").toString()) : 1;
            int size = body.get("size") != null ? Integer.parseInt(body.get("size").toString()) : 20;

            List<CommunityPost> posts = postFavoriteService.getUserFavorites(userId, page, size);
            int totalCount = postFavoriteService.getUserFavoriteCount(userId);

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("posts", posts);
            resultMap.put("count", posts.size());
            resultMap.put("totalCount", totalCount);
            resultMap.put("page", page);
            resultMap.put("size", size);
            resultMap.put("hasMore", (page * size) < totalCount);

            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取用户收藏列表失败", e);
            return createErrorResponse("获取用户收藏列表失败: " + e.getMessage());
        }
    }

    // 评论点赞相关处理方法
    private FitnessResponse handleCommentLikeToggle(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(body.get("userId").toString());
            Long commentId = Long.valueOf(body.get("commentId").toString());

            boolean result = commentLikeService.toggleCommentLike(userId, commentId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("success", result);
            resultMap.put("message", result ? "评论点赞状态切换成功" : "评论点赞状态切换失败");
            resultMap.put("userId", userId);
            resultMap.put("commentId", commentId);

            if (result) {
                // 获取更新后的点赞状态和数量
                Boolean isLiked = commentLikeService.getUserLikeStatus(userId, commentId);
                int likeCount = commentLikeService.getCommentLikeCount(commentId);

                resultMap.put("isLiked", isLiked);
                resultMap.put("likeCount", likeCount);

                log.info("评论点赞状态切换成功: userId={}, commentId={}, isLiked={}, likeCount={}",
                        userId, commentId, isLiked, likeCount);
            }

            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("切换评论点赞状态失败", e);
            return createErrorResponse("切换评论点赞状态失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleCommentLikeGetStatus(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(body.get("userId").toString());
            Long commentId = Long.valueOf(body.get("commentId").toString());

            Boolean result = commentLikeService.getUserLikeStatus(userId, commentId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("isLiked", result);
            resultMap.put("userId", userId);
            resultMap.put("commentId", commentId);
            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取评论点赞状态失败", e);
            return createErrorResponse("获取评论点赞状态失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleCommentLikeGetCount(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long commentId = Long.valueOf(body.get("commentId").toString());

            int result = commentLikeService.getCommentLikeCount(commentId);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("likeCount", result);
            resultMap.put("commentId", commentId);
            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取评论点赞数量失败", e);
            return createErrorResponse("获取评论点赞数量失败: " + e.getMessage());
        }
    }

    // 运动信息相关处理方法
    private FitnessResponse handleExerciseInfoCreate(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            com.team9.fitness.entity.ExerciseInfo exerciseInfo = objectMapper.convertValue(body.get("exerciseInfo"),
                    com.team9.fitness.entity.ExerciseInfo.class);

            ExerciseInfo createdInfo = exerciseInfoService.createExerciseInfo(exerciseInfo);
            if (createdInfo != null && createdInfo.getId() != null) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("id", createdInfo.getId());
                resultMap.put("name", createdInfo.getName());
                resultMap.put("category", createdInfo.getCategory());
                resultMap.put("description", createdInfo.getDescription());
                resultMap.put("createdAt", createdInfo.getCreatedAt());
                resultMap.put("message", "运动信息创建成功");
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("运动信息创建失败");
            }
        } catch (Exception e) {
            log.error("创建运动信息失败", e);
            return createErrorResponse("创建运动信息失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseInfoGetAll(FitnessRequest request) {
        try {
            List<ExerciseInfo> exerciseInfos = exerciseInfoService.getAllExerciseInfo();
            if (exerciseInfos != null && !exerciseInfos.isEmpty()) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("exerciseInfos", exerciseInfos);
                resultMap.put("count", exerciseInfos.size());
                return createSuccessResponse(resultMap);
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("exerciseInfos", new ArrayList<>());
                resultMap.put("count", 0);
                return createSuccessResponse(resultMap);
            }
        } catch (Exception e) {
            log.error("获取所有运动信息失败", e);
            return createErrorResponse("获取所有运动信息失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseInfoGetById(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long id = Long.valueOf(body.get("id").toString());

            ExerciseInfo exerciseInfo = exerciseInfoService.getExerciseInfoById(id);
            if (exerciseInfo != null) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("id", exerciseInfo.getId());
                resultMap.put("name", exerciseInfo.getName());
                resultMap.put("category", exerciseInfo.getCategory());
                resultMap.put("description", exerciseInfo.getDescription());
                resultMap.put("createdAt", exerciseInfo.getCreatedAt());
                resultMap.put("updatedAt", exerciseInfo.getUpdatedAt());
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("运动信息不存在");
            }
        } catch (Exception e) {
            log.error("获取运动信息失败", e);
            return createErrorResponse("获取运动信息失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseInfoGetByCategory(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String category = (String) body.get("category");

            List<ExerciseInfo> exerciseInfos = exerciseInfoService.getExerciseInfoByCategory(category);
            if (exerciseInfos != null && !exerciseInfos.isEmpty()) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("exerciseInfos", exerciseInfos);
                resultMap.put("count", exerciseInfos.size());
                resultMap.put("category", category);
                return createSuccessResponse(resultMap);
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("exerciseInfos", new ArrayList<>());
                resultMap.put("count", 0);
                resultMap.put("category", category);
                return createSuccessResponse(resultMap);
            }
        } catch (Exception e) {
            log.error("获取分类运动信息失败", e);
            return createErrorResponse("获取分类运动信息失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseInfoSearch(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String keyword = (String) body.get("keyword");

            List<ExerciseInfo> exerciseInfos = exerciseInfoService.searchExerciseInfoByName(keyword);
            if (exerciseInfos != null && !exerciseInfos.isEmpty()) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("exerciseInfos", exerciseInfos);
                resultMap.put("count", exerciseInfos.size());
                resultMap.put("keyword", keyword);
                return createSuccessResponse(resultMap);
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("exerciseInfos", new ArrayList<>());
                resultMap.put("count", 0);
                resultMap.put("keyword", keyword);
                return createSuccessResponse(resultMap);
            }
        } catch (Exception e) {
            log.error("搜索运动信息失败", e);
            return createErrorResponse("搜索运动信息失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseInfoGetCategories(FitnessRequest request) {
        try {
            List<String> categories = exerciseInfoService.getAllCategories();
            if (categories != null && !categories.isEmpty()) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("categories", categories);
                resultMap.put("count", categories.size());
                return createSuccessResponse(resultMap);
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("categories", new ArrayList<>());
                resultMap.put("count", 0);
                return createSuccessResponse(resultMap);
            }
        } catch (Exception e) {
            log.error("获取运动分类失败", e);
            return createErrorResponse("获取运动分类失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseInfoUpdate(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long id = Long.valueOf(body.get("id").toString());
            com.team9.fitness.entity.ExerciseInfo exerciseInfo = objectMapper.convertValue(body.get("exerciseInfo"),
                    com.team9.fitness.entity.ExerciseInfo.class);
            exerciseInfo.setId(id);

            ExerciseInfo updatedInfo = exerciseInfoService.updateExerciseInfo(exerciseInfo);
            if (updatedInfo != null && updatedInfo.getId() != null) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("id", updatedInfo.getId());
                resultMap.put("name", updatedInfo.getName());
                resultMap.put("category", updatedInfo.getCategory());
                resultMap.put("description", updatedInfo.getDescription());
                resultMap.put("updatedAt", updatedInfo.getUpdatedAt());
                resultMap.put("message", "运动信息更新成功");
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("运动信息更新失败");
            }
        } catch (Exception e) {
            log.error("更新运动信息失败", e);
            return createErrorResponse("更新运动信息失败: " + e.getMessage());
        }
    }

    private FitnessResponse handleExerciseInfoDelete(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long id = Long.valueOf(body.get("id").toString());

            exerciseInfoService.deleteExerciseInfo(id);
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("success", true);
            resultMap.put("message", "运动信息删除成功");
            resultMap.put("id", id);
            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("删除运动信息失败", e);
            return createErrorResponse("删除运动信息失败: " + e.getMessage());
        }
    }

    // 辅助方法
    private FitnessResponse createSuccessResponse(Object data) {
        FitnessResponse response = new FitnessResponse();
        response.setSuccess(true);
        response.setStatusCode(200);
        response.setMessage("操作成功");
        response.setData(data);
        return response;
    }

    private FitnessResponse createErrorResponse(String message) {
        FitnessResponse response = new FitnessResponse();
        response.setSuccess(false);
        response.setStatusCode(500);
        response.setMessage(message);
        return response;
    }

    /**
     * 发送响应数据
     */
    private void sendResponse(String requestId, FitnessResponse response) {
        try {
            // 确保响应对象包含正确的requestId
            if (response.getRequestId() == null || response.getRequestId().trim().isEmpty()) {
                response.setRequestId(requestId);
                log.info("设置响应requestId: {}", requestId);
            }

            // 将响应对象转换为JSON字符串
            String responseJson = objectMapper.writeValueAsString(response);
            log.info("发送响应: requestId={}, response={}", requestId, responseJson);

            // 将JSON字符串转换为字节数组
            byte[] responseData = responseJson.getBytes("UTF-8");

            // 使用DDSIF.BytesWrite发送响应数据
            ReturnCode_t result = DDSIF.BytesWrite(domainId, sendTopicName, responseData, responseData.length);
            if (result != ReturnCode_t.RETCODE_OK) {
                log.error("发送响应失败，返回码: {}", result);
            } else {
                log.info("响应发送成功: requestId={}", requestId);
            }

        } catch (Exception e) {
            log.error("发送响应失败: requestId={}", requestId, e);
        }
    }

    /**
     * 销毁资源
     */
    @PreDestroy
    public void destroy() {
        try {
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
                try {
                    if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
                        scheduler.shutdownNow();
                    }
                } catch (InterruptedException e) {
                    scheduler.shutdownNow();
                    Thread.currentThread().interrupt();
                }
            }
            log.info("ZRDDS数据监听器资源已清理");
        } catch (Exception e) {
            log.error("清理ZRDDS数据监听器资源失败", e);
        }
    }

    /**
     * 处理食物信息分类获取请求
     */
    private FitnessResponse handleFoodInfoGetCategories(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            List<String> categories = foodInfoService.getAllCategories();

            response.setSuccess(true);
            response.setMessage("获取食物分类成功");
            response.setData(Map.of("categories", categories, "count", categories.size()));
            log.info("获取食物分类成功: count={}", categories.size());

        } catch (Exception e) {
            log.error("获取食物分类失败", e);
            response.setSuccess(false);
            response.setMessage("获取食物分类失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理饮食记录营养汇总获取请求
     */
    private FitnessResponse handleDietRecordGetSummary(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String userId = request.getUserId();
            String date = (String) body.get("date");

            Map<String, Object> summary = dietRecordService.getNutritionSummaryByUserAndDate(Long.valueOf(userId),
                    date);

            response.setSuccess(true);
            response.setMessage("获取营养汇总成功");
            response.setData(summary);
            log.info("获取营养汇总成功: userId={}, date={}", userId, date);

        } catch (Exception e) {
            log.error("获取营养汇总失败", e);
            response.setSuccess(false);
            response.setMessage("获取营养汇总失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理饮食记录按用户和日期获取请求
     */
    private FitnessResponse handleDietRecordGetByUserDate(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String userId = request.getUserId();
            String date = (String) body.get("date");

            List<DietRecord> records = dietRecordService.getDietRecordsByUserAndDate(Long.valueOf(userId), date);

            response.setSuccess(true);
            response.setMessage("获取饮食记录成功");
            response.setData(Map.of("records", records, "count", records.size()));
            log.info("获取饮食记录成功: userId={}, date={}, count={}", userId, date, records.size());

        } catch (Exception e) {
            log.error("获取饮食记录失败", e);
            response.setSuccess(false);
            response.setMessage("获取饮食记录失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理获取所有食物信息请求
     */
    private FitnessResponse handleFoodInfoGetAll(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            List<FoodInfo> foodList = foodInfoService.getAllFoodInfo();

            response.setSuccess(true);
            response.setMessage("获取食物信息成功");
            response.setData(Map.of("foods", foodList, "count", foodList.size()));
            log.info("获取所有食物信息成功: count={}", foodList.size());

        } catch (Exception e) {
            log.error("获取所有食物信息失败", e);
            response.setSuccess(false);
            response.setMessage("获取所有食物信息失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理根据分类获取食物信息请求
     */
    private FitnessResponse handleFoodInfoGetByCategory(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String category = body.get("category").toString();

            List<FoodInfo> foodList = foodInfoService.getFoodInfoByCategory(category);

            response.setSuccess(true);
            response.setMessage("获取分类食物信息成功");
            response.setData(Map.of("foods", foodList, "count", foodList.size()));
            log.info("获取分类食物信息成功: category={}, count={}", category, foodList.size());

        } catch (Exception e) {
            log.error("获取分类食物信息失败", e);
            response.setSuccess(false);
            response.setMessage("获取分类食物信息失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理根据ID获取食物信息请求
     */
    private FitnessResponse handleFoodInfoGetById(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long id = Long.valueOf(body.get("id").toString());

            FoodInfo foodInfo = foodInfoService.getFoodInfoById(id);
            if (foodInfo != null) {
                response.setSuccess(true);
                response.setMessage("获取食物信息成功");
                response.setData(foodInfo);
                log.info("获取食物信息成功: id={}", id);
            } else {
                response.setSuccess(false);
                response.setMessage("食物信息不存在");
                log.warn("食物信息不存在: id={}", id);
            }

        } catch (Exception e) {
            log.error("获取食物信息失败", e);
            response.setSuccess(false);
            response.setMessage("获取食物信息失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理搜索食物信息请求
     */
    private FitnessResponse handleFoodInfoSearch(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String keyword = body.get("keyword").toString();

            List<FoodInfo> foodList = foodInfoService.searchFoodInfoByName(keyword);

            response.setSuccess(true);
            response.setMessage("搜索食物信息成功");
            response.setData(Map.of("foods", foodList, "count", foodList.size()));
            log.info("搜索食物信息成功: keyword={}, count={}", keyword, foodList.size());

        } catch (Exception e) {
            log.error("搜索食物信息失败", e);
            response.setSuccess(false);
            response.setMessage("搜索食物信息失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理饮食记录创建请求
     */
    private FitnessResponse handleDietRecordCreate(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String userId = request.getUserId();

            // 从请求体中获取饮食记录数据
            com.team9.fitness.entity.DietRecord dietRecord = objectMapper.convertValue(body.get("dietRecord"),
                    com.team9.fitness.entity.DietRecord.class);

            // 设置用户ID
            dietRecord.setUserId(Long.valueOf(userId));

            // 调用DietRecordService创建饮食记录
            DietRecord createdRecord = dietRecordService.createDietRecord(dietRecord);

            if (createdRecord != null && createdRecord.getId() != null) {
                response.setSuccess(true);
                response.setMessage("饮食记录创建成功");
                response.setData(createdRecord);
                log.info("饮食记录创建成功: userId={}, recordId={}", userId, createdRecord.getId());
            } else {
                response.setSuccess(false);
                response.setMessage("饮食记录创建失败");
                log.warn("饮食记录创建失败: userId={}", userId);
            }

        } catch (Exception e) {
            log.error("创建饮食记录失败", e);
            response.setSuccess(false);
            response.setMessage("创建饮食记录失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理帖子评论创建请求
     */
    private FitnessResponse handlePostCommentCreate(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String userId = request.getUserId();

            // 从请求体中获取评论数据 - 注意数据是嵌套在"comment"对象中的
            @SuppressWarnings("unchecked")
            Map<String, Object> commentData = (Map<String, Object>) body.get("comment");

            if (commentData == null) {
                response.setSuccess(false);
                response.setMessage("评论数据不能为空");
                log.warn("评论创建失败: 评论数据为空");
                return response;
            }

            Long postId = null;
            String content = null;
            Long parentId = null;
            Long rootId = null;

            // 安全地获取postId
            Object postIdObj = commentData.get("postId");
            if (postIdObj != null) {
                postId = Long.valueOf(postIdObj.toString());
            } else {
                response.setSuccess(false);
                response.setMessage("帖子ID不能为空");
                log.warn("评论创建失败: 帖子ID为空");
                return response;
            }

            // 安全地获取content
            Object contentObj = commentData.get("content");
            if (contentObj != null) {
                content = contentObj.toString();
            } else {
                response.setSuccess(false);
                response.setMessage("评论内容不能为空");
                log.warn("评论创建失败: 评论内容为空");
                return response;
            }

            // 安全地获取parentId
            Object parentIdObj = commentData.get("parentId");
            if (parentIdObj != null) {
                parentId = Long.valueOf(parentIdObj.toString());
            }

            // 安全地获取rootId
            Object rootIdObj = commentData.get("rootId");
            if (rootIdObj != null) {
                rootId = Long.valueOf(rootIdObj.toString());
            }
            
            log.info("ZRDDSDataListener处理评论创建: postId={}, userId={}, parentId={}, rootId={}, content={}", 
                    postId, userId, parentId, rootId, content);

            // 调用PostCommentService创建评论
            PostComment createdComment = postCommentService.addCommentByZRDDS(Long.valueOf(userId), postId, content, parentId, rootId);

            if (createdComment != null && createdComment.getId() != null) {
                response.setSuccess(true);
                response.setStatusCode(200);
                response.setMessage("评论创建成功");
                response.setData(createdComment);
                log.info("评论创建成功: userId={}, postId={}, commentId={}", userId, postId, createdComment.getId());
            } else {
                response.setSuccess(false);
                response.setMessage("评论创建失败");
                log.warn("评论创建失败: userId={}, postId={}", userId, postId);
            }

        } catch (Exception e) {
            log.error("创建评论失败", e);
            response.setSuccess(false);
            response.setMessage("创建评论失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理获取帖子评论请求
     */
    private FitnessResponse handlePostCommentGetByPost(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String currentUserId = request.getUserId();

            Long postId = Long.valueOf(body.get("postId").toString());

            // 调用PostCommentService获取评论列表
            List<PostComment> comments = postCommentService.getCommentsByPostId(postId, Long.valueOf(currentUserId));

            response.setSuccess(true);
            response.setStatusCode(200);
            response.setMessage("获取评论成功");
            response.setData(Map.of("comments", comments, "count", comments.size()));
            log.info("获取评论成功: postId={}, count={}", postId, comments.size());

        } catch (Exception e) {
            log.error("获取评论失败", e);
            response.setSuccess(false);
            response.setMessage("获取评论失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理获取评论详情请求
     */
    private FitnessResponse handlePostCommentGetById(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String currentUserId = request.getUserId();

            Long id = Long.valueOf(body.get("id").toString());

            // 调用PostCommentService获取评论详情
            Optional<PostComment> commentOpt = postCommentService.getCommentById(id, Long.valueOf(currentUserId));

            if (commentOpt.isPresent()) {
                PostComment comment = commentOpt.get();
                response.setSuccess(true);
                response.setStatusCode(200);
                response.setMessage("获取评论详情成功");
                response.setData(comment);
                log.info("获取评论详情成功: id={}", id);
            } else {
                response.setSuccess(false);
                response.setStatusCode(404);
                response.setMessage("评论不存在");
                log.warn("评论不存在: id={}", id);
            }

        } catch (Exception e) {
            log.error("获取评论详情失败", e);
            response.setSuccess(false);
            response.setMessage("获取评论详情失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理获取评论回复请求
     */
    private FitnessResponse handlePostCommentGetReplies(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            String currentUserId = request.getUserId();

            Long commentId = Long.valueOf(body.get("commentId").toString());

            // 调用PostCommentService获取回复列表
            List<PostComment> replies = postCommentService.getRepliesByCommentId(commentId, Long.valueOf(currentUserId));

            response.setSuccess(true);
            response.setStatusCode(200);
            response.setMessage("获取回复成功");
            response.setData(Map.of("replies", replies, "count", replies.size()));
            log.info("获取回复成功: commentId={}, count={}", commentId, replies.size());

        } catch (Exception e) {
            log.error("获取回复失败", e);
            response.setSuccess(false);
            response.setMessage("获取回复失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理获取评论数量请求
     */
    private FitnessResponse handlePostCommentGetCount(FitnessRequest request) {
        FitnessResponse response = new FitnessResponse();

        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> body = (Map<String, Object>) request.getBody();

            Long postId = Long.valueOf(body.get("postId").toString());

            // 调用PostCommentService获取评论列表并计算数量
            List<PostComment> comments = postCommentService.getCommentsByPostId(postId, null);
            int count = comments != null ? comments.size() : 0;

            Map<String, Object> result = new HashMap<>();
            result.put("postId", postId);
            result.put("commentCount", count);

            response.setSuccess(true);
            response.setStatusCode(200);
            response.setMessage("获取评论数量成功");
            response.setData(result);
            log.info("获取评论数量成功: postId={}, count={}", postId, count);

        } catch (Exception e) {
            log.error("获取评论数量失败", e);
            response.setSuccess(false);
            response.setMessage("获取评论数量失败: " + e.getMessage());
        }

        return response;
    }

    /**
     * 处理获取用户评论列表请求
     */
    private FitnessResponse handlePostCommentGetUserComments(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(body.get("userId").toString());
            int page = body.get("page") != null ? Integer.parseInt(body.get("page").toString()) : 1;
            int size = body.get("size") != null ? Integer.parseInt(body.get("size").toString()) : 20;

            List<PostComment> comments = postCommentService.getUserComments(userId, page, size);
            int totalCount = postCommentService.getUserCommentCount(userId);

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("comments", comments);
            resultMap.put("count", comments.size());
            resultMap.put("totalCount", totalCount);
            resultMap.put("page", page);
            resultMap.put("size", size);
            resultMap.put("hasMore", (page * size) < totalCount);

            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取用户评论列表失败", e);
            return createErrorResponse("获取用户评论列表失败: " + e.getMessage());
        }
    }

    /**
     * 处理删除评论请求
     */
    private FitnessResponse handlePostCommentDelete(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long commentId = Long.valueOf(body.get("commentId").toString());
            Long userId = Long.valueOf(body.get("userId").toString());

            boolean success = postCommentService.deleteComment(commentId, userId);
            if (success) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("success", true);
                resultMap.put("message", "评论删除成功");
                resultMap.put("commentId", commentId);
                return createSuccessResponse(resultMap);
            } else {
                return createErrorResponse("评论删除失败，可能没有权限或评论不存在");
            }
        } catch (Exception e) {
            log.error("删除评论失败", e);
            return createErrorResponse("删除评论失败: " + e.getMessage());
        }
    }

    /**
     * 处理快速获取帖子详情请求（仅正文 + 前N条评论）
     */
    private FitnessResponse handleCommunityGetPostQuick(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long postId = body.get("postId") != null ? Long.valueOf(body.get("postId").toString()) : null;
            Long currentUserId = body.get("currentUserId") != null ? Long.valueOf(body.get("currentUserId").toString()) : null;
            Integer commentLimit = body.get("commentLimit") != null ? Integer.valueOf(body.get("commentLimit").toString()) : 10;

            if (postId == null) {
                return createErrorResponse("帖子ID不能为空");
            }

            log.info("快速获取帖子详情: postId={}, currentUserId={}, commentLimit={}", postId, currentUserId, commentLimit);

            // 获取帖子详情
            Optional<CommunityPost> postOpt = communityPostService.getPostById(postId, currentUserId);
            if (!postOpt.isPresent()) {
                return createErrorResponse("帖子不存在或已被删除");
            }

            CommunityPost post = postOpt.get();

            // 获取前N条评论
            List<PostComment> comments = postCommentService.getCommentsByPostIdWithLimit(postId, commentLimit, currentUserId);
            int totalComments = postCommentService.countByPostId(postId);

            log.info("快速获取帖子详情成功: postId={}, 评论数量={}, 总评论数={}", postId, comments.size(), totalComments);

            // 构建响应数据
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("post", post);
            resultMap.put("comments", comments);
            resultMap.put("totalComments", totalComments);

            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("快速获取帖子详情失败", e);
            return createErrorResponse("快速获取帖子详情失败: " + e.getMessage());
        }
    }

    /**
     * 处理获取帖子评论请求（分页加载）
     */
    private FitnessResponse handleCommunityGetPostComments(FitnessRequest request) {
        try {
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long postId = body.get("postId") != null ? Long.valueOf(body.get("postId").toString()) : null;
            Long currentUserId = body.get("currentUserId") != null ? Long.valueOf(body.get("currentUserId").toString()) : null;
            Integer offset = body.get("offset") != null ? Integer.valueOf(body.get("offset").toString()) : 0;
            Integer limit = body.get("limit") != null ? Integer.valueOf(body.get("limit").toString()) : 20;

            if (postId == null) {
                return createErrorResponse("帖子ID不能为空");
            }

            log.info("获取帖子评论: postId={}, currentUserId={}, offset={}, limit={}", postId, currentUserId, offset, limit);

            // 获取分页评论
            List<PostComment> comments = postCommentService.getCommentsByPostIdWithPagination(postId, offset, limit, currentUserId);
            int totalComments = postCommentService.countByPostId(postId);
            boolean hasMore = (offset + comments.size()) < totalComments;

            log.info("获取帖子评论成功: postId={}, 返回评论数={}, 总评论数={}, 还有更多={}", postId, comments.size(), totalComments, hasMore);

            // 构建响应数据
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("comments", comments);
            resultMap.put("hasMore", hasMore);
            resultMap.put("totalComments", totalComments);

            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取帖子评论失败", e);
            return createErrorResponse("获取帖子评论失败: " + e.getMessage());
        }
    }

    /**
     * 处理头像上传请求
     */
    private FitnessResponse handleAvatarUpload(FitnessRequest request) {
        try {
            log.info("开始处理头像上传请求 - requestId: {}", request.getRequestId());
            
            Map<String, Object> body = (Map<String, Object>) request.getBody();
            Long userId = Long.valueOf(request.getUserId());
            String fileName = (String) body.get("fileName");
            String contentType = (String) body.get("contentType");
            Long fileSize = body.get("fileSize") != null ? Long.valueOf(body.get("fileSize").toString()) : null;
            String base64Data = (String) body.get("base64Data");

            log.info("头像上传参数 - userId: {}, fileName: {}, contentType: {}, fileSize: {}, base64Data长度: {}", 
                    userId, fileName, contentType, fileSize, base64Data != null ? base64Data.length() : 0);

            if (fileName == null || fileName.isEmpty()) {
                log.error("文件名为空");
                return createErrorResponse("文件名不能为空");
            }
            if (base64Data == null || base64Data.isEmpty()) {
                log.error("文件数据为空");
                return createErrorResponse("文件数据不能为空");
            }

            log.info("调用UserAvatarService上传头像 - userId: {}", userId);
            
            // 上传头像
            UserAvatar userAvatar = userAvatarService.uploadAvatarFromBase64(userId, fileName, contentType, fileSize, base64Data);

            log.info("头像上传成功 - userId: {}, avatarUrl: {}", userId, userAvatar.getAvatarUrl());

            // 构建响应数据
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("avatarUrl", userAvatar.getAvatarUrl());
            resultMap.put("fileName", userAvatar.getFileName());
            resultMap.put("fileSize", userAvatar.getFileSize());
            resultMap.put("uploadTime", userAvatar.getUploadTime());

            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("头像上传失败 - requestId: {}", request.getRequestId(), e);
            return createErrorResponse("头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 处理获取头像请求
     */
    private FitnessResponse handleAvatarGet(FitnessRequest request) {
        try {
            Long userId = Long.valueOf(request.getUserId());

            log.info("获取用户头像: userId={}", userId);

            // 获取用户头像
            UserAvatar userAvatar = userAvatarService.getActiveAvatar(userId);

            if (userAvatar == null) {
                return createErrorResponse("用户没有设置头像");
            }

            log.info("获取用户头像成功: userId={}, avatarUrl={}", userId, userAvatar.getAvatarUrl());

            // 构建响应数据
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("avatarUrl", userAvatar.getAvatarUrl());
            resultMap.put("fileName", userAvatar.getFileName());
            resultMap.put("fileSize", userAvatar.getFileSize());
            resultMap.put("uploadTime", userAvatar.getUploadTime());
            resultMap.put("isDefault", false);

            return createSuccessResponse(resultMap);
        } catch (Exception e) {
            log.error("获取用户头像失败", e);
            return createErrorResponse("获取用户头像失败: " + e.getMessage());
        }
    }

    /**
     * 处理删除头像请求
     */
    private FitnessResponse handleAvatarDelete(FitnessRequest request) {
        try {
            Long userId = Long.valueOf(request.getUserId());

            log.info("删除用户头像: userId={}", userId);

            // 删除用户头像
            boolean deleted = userAvatarService.deleteAvatar(userId);

            if (!deleted) {
                return createErrorResponse("删除头像失败");
            }

            log.info("删除用户头像成功: userId={}", userId);

            return createSuccessResponse("头像删除成功");
        } catch (Exception e) {
            log.error("删除用户头像失败", e);
            return createErrorResponse("删除用户头像失败: " + e.getMessage());
        }
    }
}
